package web.comment;

import bean.Comment;
import bean.Union;
import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.CommentEntity;
import entity.VideoEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "XiangsiVoideList", urlPatterns = "/dao/ddd")
public class XiangsiVoideList extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        int vid = Integer.parseInt(FANREN.getJson(request));
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        VideoEntity videoEntity = em.find(VideoEntity.class,vid);
        Query query = em.createQuery("select v from VideoEntity v where v.tid.tid =" + videoEntity.getTid().getTid());
        List<VideoEntity> list = query.getResultList();

        List<Video> videoList = new ArrayList<>();
        for (int i=0,j=0; i<10&&j<list.size(); i++,j++) {
            if(list.get(j).getTid().getName().equals(videoEntity.getTid().getName())) {
                Video video = new Video();
                video.setVid(String.valueOf(list.get(j).getVid()));
                video.setName(list.get(j).getName());
                video.setAuthor("" + list.get(j).getUid().getName());
                video.setIntroduce(list.get(j).getIntroduce());
                video.setTime(list.get(j).getTime());
                video.setType("" + list.get(j).getTid().getName());
                video.setViews(list.get(j).getViews());
                video.setAv(list.get(j).getAv());
                video.setImgUrl(list.get(j).getImgUrl().equals("") ? "http://localhost:8080/img/default.jpg" : list.get(j).getImgUrl());
                videoList.add(video);
            }
        }
        response.getWriter().write(URLEncoder.encode(JSON.toJSONString(videoList),StandardCharsets.UTF_8));
    }
}
